import { PlusOutlined } from '@ant-design/icons';
import { ModalForm, ProFormSelect, ProFormUploadButton } from '@ant-design/pro-components';
import { useState } from 'react';
import { Button, message } from 'antd';
import type { RcFile } from 'antd/lib/upload';
import DownloadTemplate from './DownloadTemplate';
import type { CreateTaskType } from '../data.d';
import { TaskType } from '../data.d';
import { createTask, uploadTaskPreFile } from '../service';
import { useModel } from 'umi';
import { Role, Auths } from '@/utils/types.d';
import { queryCompanies } from '@/pages/SystemUser/service';
import { queryParkinglotNames } from '@/pages/Parking/Spot/service';

export default (props: { func: () => void }) => {
  const { initialState } = useModel('@@initialState');
  const currUser = initialState?.currentUser;
  const userRole = currUser?.role;
  const auths = currUser?.auth ? new Set(currUser.auth.batchTask || []) : new Set();
  const ifPkSpotImp = auths.has(Auths.PKSPOT_IMP);
  const ifPkLotImp = auths.has(Auths.PKLOT_IMP);
  const ifSensorBind = auths.has(Auths.SENSOR_BIND);
  const ifSensorCreate = auths.has(Auths.SENSOR_DEVICE_IMP);
  const ifPatrolCreate = auths.has(Auths.PATROL_DEVICE_IMP);
  const ifOrderImport = auths.has(Auths.ORDER_IMP);
  const ifOutCar = auths.has(Auths.OUT_CAR);

  const handleOptions = () => {
    const options: { value: string; label: string }[] = [];
    if (ifPkLotImp) options.push({ value: TaskType.CREATE_PKLOT, label: '批量创建路段' });
    if (ifPkSpotImp) options.push({ value: TaskType.CREATE_PKSPOT, label: '批量创建泊位' });
    if (ifSensorBind) options.push({ value: TaskType.BIND_SENSOR, label: '批量绑定地磁' });
    if (ifSensorCreate) options.push({ value: TaskType.CREATE_SENSOR, label: '批量创建地磁设备' });
    if (ifPatrolCreate) options.push({ value: TaskType.CREATE_PATROL, label: '批量创建巡检设备' });
    if (ifOrderImport) options.push({ value: TaskType.IMPORT_ORDER, label: '批量导入欠费订单' });
    if (ifOutCar) options.push({ value: TaskType.OUT_CAR, label: '批量驶出订单' });
    return options;
  };
  const [prepareId, setPrepareId] = useState<string>('');
  const [taskType, setTaskType] = useState<string>('');

  return (
    <ModalForm<{
      type: string;
      ownerId: string;
      parkingLotId?: string;
      parkingLotIds?: string[];
    }>
      modalProps={{
        destroyOnClose: true,
        maskClosable: false,
      }}
      layout="horizontal"
      labelCol={{ span: 6 }}
      wrapperCol={{ span: 16 }}
      width="40vw"
      title="创建批量任务"
      trigger={
        <Button type="primary">
          <PlusOutlined /> 创建任务
        </Button>
      }
      onFinish={async (values) => {
        if (values.type != TaskType.OUT_CAR && (!prepareId || prepareId.length < 1)) {
          message.error({ content: '请上传文件', key: 'upload_task' });
          return false;
        }
        const data2create: CreateTaskType = {
          prepareId,
          type: values.type as TaskType,
          ownerId: values.ownerId,
        };
        if (values.type == TaskType.IMPORT_ORDER) {
          if (!values.parkingLotId) {
            message.error({ content: '请选择订单所在路段', key: 'upload_task' });
            return false;
          }
          data2create.extraData = { parkingLotId: values.parkingLotId };
        }
        if (values.type == TaskType.OUT_CAR) {
          if (!values.parkingLotIds || values.parkingLotIds?.length < 1) {
            message.error({ content: '请选择订单所在路段', key: 'upload_task' });
            return false;
          }
          data2create.extraData = { parkingLotIds: values.parkingLotIds };
        }
        const res = await createTask(data2create);
        if (res.success) {
          props.func();
          message.success({
            content: res.message,
            key: 'upload_task',
          });
          return true;
        }
        message.error({
          content: res.message,
          key: 'upload_task',
        });
        return false;
      }}
    >
      <ProFormSelect
        label="任务类型"
        name="type"
        placeholder="请选择任务类型"
        rules={[{ required: true, message: '请选择任务类型' }]}
        fieldProps={{
          onChange: (value) => {
            setTaskType(value);
          },
        }}
        options={handleOptions()}
        width="lg"
      />
      {userRole === Role.ADMIN && (
        <ProFormSelect
          name="ownerId"
          label="选择用户"
          rules={[{ required: true, message: '请选择用户' }]}
          width="lg"
          debounceTime={300}
          showSearch
          placeholder="请选择用户"
          request={(val) => queryCompanies(val.keyWords)}
        />
      )}
      {taskType == TaskType.IMPORT_ORDER && (
        <ProFormSelect
          label="选择路段"
          name="parkingLotId"
          debounceTime={300}
          required
          placeholder="请选择路段"
          showSearch
          request={(val) => queryParkinglotNames(val.keyWords)}
          width="lg"
        />
      )}
      {taskType == TaskType.OUT_CAR && (
        <ProFormSelect
          label="选择路段"
          name="parkingLotIds"
          debounceTime={300}
          required
          placeholder="请选择路段"
          mode="multiple"
          rules={[
            {
              required: true,
              validator: (_, val) => {
                if (!val) return Promise.reject(new Error('请选择路段'));
                if (val && val.length <= 5) {
                  return Promise.resolve(val);
                }
                return Promise.reject(new Error('路段最多选择5个'));
              },
            },
          ]}
          showSearch
          width="lg"
          request={(val) => queryParkinglotNames(val.keyWords)}
        />
      )}
      {/* <ProFormUploadButton
        label="上传文件"
        title="xlsx格式，大小小于200K"
        name="create_multi"
        accept=".xlsx"
        action="/api/batch-task/v1.0.0/pre-file"
        fieldProps={{
          name: 'create_multi',
          showUploadList: false,
          beforeUpload: (file: RcFile): Promise<void> =>
            new Promise((resolve, rejects) => {
              const { name } = file;

              // .xlsx*表示匹配所有带有 .xlsx 的字段，$表示匹配字符串结尾位置
              const nameRegExp = new RegExp('.xlsx*$');
              const isXlsx = nameRegExp.test(name);
              const isLt200K = file.size / 1024 < 200;
              if (!isXlsx) {
                message.error({
                  content: '文件类型错误, 请上传一个xlsx表格文件',
                  key: 'upload_task',
                });
                rejects();
                return;
              }
              if (!isLt200K) {
                message.error({
                  content: '文件过大，请上传一个小于200k的文件',
                  key: 'upload_task',
                });
                rejects();
                return;
              }
              resolve();
            }),
        }}
        onChange={(info) => {
          const { status, response, name } = info.file;
          if (status === 'uploading') {
            message.loading({
              content: '文件上传中...',
              key: 'upload_task',
            });
          }
          if (status === 'done' && response?.code === 0) {
            setPrepareId(response?.data);
            message.success({
              content: '上传成功',
              key: 'upload_task',
            });
            return true;
          } else if (status === 'error' || response?.code) {
            const msg = response?.message || '';
            message.error({ content: `${name}上传失败。${msg}`, key: 'upload_info' });
            return false;
          }
          return false;
        }}
      /> */}
      {taskType != TaskType.OUT_CAR && (
        <ProFormUploadButton
          label="上传文件"
          title="xlsx格式，大小小于1M"
          name="create_multi"
          accept=".xlsx"
          fieldProps={{
            showUploadList: false,
            customRequest: async (abc) => {
              message.loading({
                content: '文件上传中...',
                key: 'upload_task',
              });
              const formData = new FormData();
              formData.append('create_multi', abc.file);
              const res = await uploadTaskPreFile(formData);
              if (res.success) {
                props.func();
                setPrepareId(res?.data);
                message.success({
                  content: '上传成功',
                  key: 'upload_task',
                });
                return true;
              }
              message.error({
                content: `${name}上传失败。${res.message}`,
                key: 'upload_task',
              });
              return false;
            },
            beforeUpload: (file: RcFile): Promise<void> =>
              new Promise((resolve, rejects) => {
                const { name } = file;

                // .xlsx*表示匹配所有带有 .xlsx 的字段，$表示匹配字符串结尾位置
                const nameRegExp = new RegExp('.xlsx*$');
                const isXlsx = nameRegExp.test(name);
                const isLt1M = file.size < 1024 * 1024;
                if (!isXlsx) {
                  message.error({
                    content: '文件类型错误, 请上传一个xlsx表格文件',
                    key: 'upload_task',
                  });
                  rejects();
                  return;
                }
                if (!isLt1M) {
                  message.error({
                    content: '文件过大，请上传一个小于1M的文件',
                    key: 'upload_task',
                  });
                  rejects();
                  return;
                }
                resolve();
              }),
          }}
          // onChange={(info) => {
          //   const { status, response, name } = info.file;
          //   if (status === 'uploading') {
          //     message.loading({
          //       content: '文件上传中...',
          //       key: 'upload_task',
          //     });
          //   }
          //   if (status === 'done' && response?.code === 0) {
          //     setPrepareId(response?.data);
          //     message.success({
          //       content: '上传成功',
          //       key: 'upload_task',
          //     });
          //     return true;
          //   } else if (status === 'error' || response?.code) {
          //     const msg = response?.message || '';
          //     message.error({ content: `${name}上传失败。${msg}`, key: 'upload_info' });
          //     return false;
          //   }
          //   return false;
          // }}
        />
      )}
      <div
        style={{
          margin: '0 auto',
          width: '80%',
          padding: '15px 8px ',
          background: '#f4f6fa',
        }}
      >
        <div>如果您没有批量模板文件，请点击下载：</div>
        <DownloadTemplate type="spot" />
        <DownloadTemplate type="lot" />
        <DownloadTemplate type="bind_sensor" />
        <DownloadTemplate type="create_sensor" />
        <DownloadTemplate type="create_patrol" />
        <DownloadTemplate type="import_order" />
        <div style={{ margin: '10px 0 5px' }}>
          使用excel编辑模板时，请确认输入的内容为文本格式。符号请在英文状态下输入。
        </div>
        <div>泊位的创建不建议使用批量任务，请使用泊位测绘工具现场逐一录入。</div>
      </div>
    </ModalForm>
  );
};
